package com.tydic.portal.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tydic.borderer.domain.MutualHelpOrganization;
import com.tydic.borderer.domain.MutualHelpOrganizationMember;
import com.tydic.borderer.domain.bo.AddMutualHelpOrganizationMemberBo;
import com.tydic.borderer.domain.bo.MutualHelpOrganizationBo;
import com.tydic.borderer.domain.bo.QueryMutualHelpOrganizationBo;
import com.tydic.borderer.domain.vo.MutualHelpOrganizationMemberVo;
import com.tydic.borderer.domain.vo.MutualHelpOrganizationVo;
import com.tydic.borderer.listener.MutualHelpOrganizationListener;
import com.tydic.borderer.listener.MutualHelpOrganizationMemberListener;
import com.tydic.borderer.service.IMutualHelpOrganizationService;
import com.tydic.common.core.domain.R;
import com.tydic.common.core.exception.api.ApiException;
import com.tydic.common.mybatis.core.page.TableDataInfo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Validated
@RequiredArgsConstructor
@RequestMapping(value = "/portal/mutualHelpOrganization")

public class MutualHelpOrganizationController {
    private final IMutualHelpOrganizationService mutualHelpOrganizationService;

    /**
     * 新增互助组信息
     */
    @PostMapping("/insert")
    public R insert(@Valid @RequestBody MutualHelpOrganizationBo mutualHelpOrganizationRequest) {
        mutualHelpOrganizationRequest.setId(IdUtil.getSnowflakeNextIdStr());
        mutualHelpOrganizationService.save(mutualHelpOrganizationRequest);
        return R.ok();
    }

    /**
     * 修改互助组信息
     */
    @PostMapping("/update")
    public R update(@Valid @RequestBody MutualHelpOrganizationBo mutualHelpOrganizationRequest) {
        if (mutualHelpOrganizationService.get(mutualHelpOrganizationRequest.getId()) == null) {
            throw new ApiException("该互助组信息不存在");
        }
        mutualHelpOrganizationService.save(mutualHelpOrganizationRequest);
        return R.ok();
    }


    /**
     * 互助组信息详情
     */
    @GetMapping("/get")
    public R get(@NotBlank(message = "请传入互助组信息ID") @RequestParam("id") String id) {
        MutualHelpOrganization mutualHelpOrganization = mutualHelpOrganizationService.get(id);
        if (mutualHelpOrganization == null) {
            throw new ApiException("互助组信息不存在");
        }
        MutualHelpOrganizationVo mutualHelpOrganizationResponse = new MutualHelpOrganizationVo();
        BeanUtils.copyProperties(mutualHelpOrganization, mutualHelpOrganizationResponse);
        List<MutualHelpOrganizationMemberVo> members = mutualHelpOrganizationService.getMembers(id).stream().map(item -> {
            MutualHelpOrganizationMemberVo mutualHelpOrganizationMemberResponse = new MutualHelpOrganizationMemberVo();
            BeanUtils.copyProperties(item, mutualHelpOrganizationMemberResponse);
            return mutualHelpOrganizationMemberResponse;
        }).collect(Collectors.toList());
        mutualHelpOrganizationResponse.setMembers(new ArrayList<>(members));
        return R.ok(mutualHelpOrganizationResponse);
    }


    /**
     * 删除互助组信息
     */
    @GetMapping("/delete")
    public R delete(@NotBlank(message = "请传入互助组信息ID") @RequestParam("id") String id) {
        MutualHelpOrganization mutualHelpOrganization = mutualHelpOrganizationService.get(id);
        if (mutualHelpOrganization == null) {
            throw new ApiException("互助组信息不存在");
        }
        mutualHelpOrganizationService.delete(id);
        return R.ok();
    }


    /**
     * 互助组信息列表
     */
    @PostMapping("/page")
    public R page(@Valid @RequestBody QueryMutualHelpOrganizationBo mutualHelpOrganizationQueryRequest) {
        Page<MutualHelpOrganization> page = mutualHelpOrganizationService.page(mutualHelpOrganizationQueryRequest);
        return R.ok(TableDataInfo.build(page));
    }


    @PostMapping("/importExcel")
    /**
     * 导入excel
     */
    public R importExcel(@RequestParam("file") MultipartFile multipartFile) {
        List<MutualHelpOrganization> mutualHelpOrganizations = new ArrayList<>();
        List<MutualHelpOrganizationMember> mutualHelpOrganizationMembers = new ArrayList<>();
        try (ExcelReader excelReader = EasyExcel.read(multipartFile.getInputStream()).build()) {
            ReadSheet readSheet1 = EasyExcel.readSheet(0).head(MutualHelpOrganization.class).registerReadListener(new MutualHelpOrganizationListener(mutualHelpOrganizations)).build();
            ReadSheet readSheet2 = EasyExcel.readSheet(1).head(MutualHelpOrganizationMember.class).registerReadListener(new MutualHelpOrganizationMemberListener(mutualHelpOrganizationMembers)).build();
            excelReader.read(readSheet1, readSheet2);
            mutualHelpOrganizationService.save(mutualHelpOrganizations.get(0), mutualHelpOrganizationMembers);
        } catch (Exception e) {
            log.error("读取excel异常", e);
            throw new ApiException("导入互助组数据异常");
        }
        return R.ok();
    }

    @PostMapping("/addMember")
    /**
     * 添加边民
     */
    public R addMember(@RequestBody @Valid AddMutualHelpOrganizationMemberBo addMutualHelpOrganizationMemberRequest) {
        mutualHelpOrganizationService.saveMember(addMutualHelpOrganizationMemberRequest);
        return R.ok();
    }


    @GetMapping("/deleteMember")
    /**
     * 删除边民
     */
    public R deleteMember(@RequestParam("id") @NotBlank(message = "互助组边民ID") String id) {
        MutualHelpOrganizationMember mutualHelpOrganizationMember = mutualHelpOrganizationService.getMember(id);
        if (mutualHelpOrganizationMember == null) {
            throw new ApiException("该互助组成员不存在");
        }
        mutualHelpOrganizationService.deleteMember(id);
        return R.ok();
    }

    @GetMapping("/downloadTemplate")
    /**
     * 下载互助组模板
     */
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "互助组导入模板.xlsx";
        String filePath = "templates/" + fileName;
        Resource resource = new ClassPathResource(filePath);
        try (InputStream inputStream = resource.getInputStream()) {
            byte[] bytes = IoUtil.readBytes(inputStream);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.addHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'" + URLEncodeUtil.encode(fileName));
            try (ServletOutputStream stream = response.getOutputStream()) {
                stream.write(bytes);
                stream.flush();
            }
        } catch (Exception e) {
            log.error("下载模板异常", e);
            throw new ApiException("下载失败，请重试");
        }
    }

}
